package com.chaodev.base.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.dto.SubMitExamPaperDto;
import com.chaodev.base.dto.WenJuanPDto;
import com.chaodev.base.model.DataPageVO;
import com.chaodev.base.model.Result;
import com.chaodev.base.model.ResultEnum;
import com.chaodev.base.model.UserInfo;
import com.chaodev.base.model.wenjuan.*;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.service.WenJuanService;
import com.chaodev.base.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * vcbase
 *
 * @author 95634
 * @描述
 * @date 2023/5/23 13:40
 **/
@Api(value = "问卷接口", description = "该接口集成了问卷接口的相关接口", tags = "wenjuan")
@RestController
@RequestMapping("wenjuan")
public class WenJuanController {
    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;

    @Autowired
    private WenJuanService wenjuanService;

    @PostMapping("/examPaperQuery")
    @ApiOperation(
            value = "获取问卷列表",//简要说明
            notes = "获取当前登录下的问卷"//详细说明
    )
    public Result examPaperQuery(@RequestBody DataPageVO dataPageVO, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            if (null == userInfo) {
                return Result.TokenExp();
            }
            PageInfo<Paper> list = wenjuanService.examPaperQuery(dataPageVO.getPage(), dataPageVO.getRows(), userInfo.getUserId());
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("获取数据成功");
            result.setData(list);
            logService.logAdd(null, "获取问卷分页列表", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(null, "获取问卷分页列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
    @PostMapping("/getUserScoreList")
    public Result getUserScoreList(@RequestBody UserScore userScore, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();

        List<UserScore> userScoreList = wenjuanService.getUserScoreList(userScore);
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMsg("获取数据成功");
        result.setData(userScoreList);
        return result;
    }

    @PostMapping("/examPaperAdd")
    @ApiOperation(
            value = "添加问卷",//简要说明
            notes = "当前登录的账号添加问卷"//详细说明
    )
    public Result examPaperAdd(@RequestBody Paper wenJuan,
                               HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        //token校验
        String token = request.getHeader("token");
        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        try {
            if (null == userInfo) {
                return Result.TokenExp();
            }
            wenJuan.setCreateUser(userInfo.getUserId());
            wenjuanService.save(wenJuan);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("添加成功");

        } catch (Exception exception) {
            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
        } finally {
            //添加日志
            logService.logAdd(null, "添加问卷", result.getCode().toString(), result.toString(), userInfo, request);
            return result;
        }
    }

    @PostMapping("/examPaperEdit")
    @ApiOperation(
            value = "修改问卷",//简要说明
            notes = "修改问卷信息"//详细说明
    )
    public Result examPaperEdit(@RequestBody Paper wenJuan,
                                HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        //token校验
        String token = request.getHeader("token");
        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        try {
            if (null == userInfo) {
                return Result.TokenExp();
            }
            Paper sysWenJuan = wenjuanService.getExamPaper(String.valueOf(wenJuan.getId()));

            sysWenJuan.setPaperName(wenJuan.getPaperName());
            sysWenJuan.setDsc(wenJuan.getDsc());
            wenjuanService.update(sysWenJuan);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("修改成功");
        } catch (Exception exception) {
            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
        } finally {
            //添加日志
            logService.logAdd(null, "修改问卷信息", result.getCode().toString(), result.toString(), userInfo, request);
            return result;
        }
    }

    @ApiOperation(value = "获取预览试卷信息")
    @PostMapping("/editExamPaper")
    public Result editExamPaper(@RequestParam(value = "id", required = true) String paperid,
                                HttpServletRequest request, HttpServletResponse hresponse) {
        Result result = new Result();
        //token校验
//        String token = request.getHeader("token");
//        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        try {
//            if (null == userInfo) {
//                return Result.TokenExp();
//            }
            if (null == paperid || "".equals(paperid)) {
                return Result.error("参数不能为空");
            }

            List<Map<String, Object>> recordList = wenjuanService.editExamPapers(paperid);
            if (null == recordList) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("获取数据失败！");
                return result;
            }
            JSONArray jsonArray = new JSONArray();
            JSONArray jsonArraySon = new JSONArray();
            JSONObject jsonObjectSon;
            String question_id = "";
            for (int i = 0; i < recordList.size(); i++) {
                Map<String, Object> record = recordList.get(i);
                String tempquestion_id = record.get("question_id").toString();


                if (!question_id.equals(tempquestion_id)) {
                    question_id = tempquestion_id;
                    jsonArraySon = new JSONArray();

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("paper_id", record.get("paper_id"));
                    jsonObject.put("paper_name", record.get("paper_name"));
                    jsonObject.put("question_id", record.get("question_id"));
                    jsonObject.put("question_name", record.get("question_name"));
                    jsonObject.put("question_class", record.get("question_class"));
                    jsonObject.put("question_img", record.get("question_img"));

                    jsonObjectSon = new JSONObject();
                    jsonObjectSon.put("answer_id", record.get("answer_id"));
                    jsonObjectSon.put("answer_name", record.get("answer_name"));
                    jsonObjectSon.put("checked", false);
                    jsonArraySon.add(jsonObjectSon);

                    jsonObject.put("answers", jsonArraySon);
                    jsonArray.add(jsonObject);

                } else {
                    jsonObjectSon = new JSONObject();
                    jsonObjectSon.put("answer_id", record.get("answer_id"));
                    jsonObjectSon.put("answer_name", record.get("answer_name"));
                    jsonObjectSon.put("checked", false);
                    jsonArraySon.add(jsonObjectSon);
                }

            }
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("获取数据成功");
            result.setData(jsonArray);

        } catch (Exception e) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @ApiOperation("问卷删除")
    @PostMapping("examPaperDel")
    public Result examPaperDel(Paper wenJuan,
                               HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        Result result = new Result();
        if (null == userInfo) {
            result.setCode(ResultEnum.EREOR.getCode());
            result.setMsg("凭证已过期，请重新登录");
            return result;
        }
        if (null == wenJuan.getId() && "".equals(wenJuan.getId())) {
            result.setCode(ResultEnum.FAILURE.getCode());
            result.setData(wenJuan);
            result.setMsg("操作的记录不存在！");
            return result;
        }
        wenJuan = wenjuanService.getExamPaper(String.valueOf(wenJuan.getId()));
        if (wenjuanService.examPaperDel(String.valueOf(wenJuan.getId()))) {
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData("");
            result.setMsg("删除成功！");
        } else {
            result.setCode(ResultEnum.FAILURE.getCode());
            result.setData("");
            result.setMsg("删除失败！");
        }
        return result;
    }


    @ApiOperation("获取当前用户的问卷信息")
    @PostMapping("getExamPaperInfo")
    public Result getExamPaperInfo(@RequestBody DataPageVO dataPageVO, HttpServletRequest request) {
        String token = request.getHeader("token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        Result result = new Result();
        try {
            if (userInfo == null) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("凭证已过期，请重新登录");
            } else {
                if (userInfo.getUserId() != null) {
                    dataPageVO.setUserId(userInfo.getUserId());
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg("获取数据成功");
                    result.setData(wenjuanService.getPaperInfo(dataPageVO));
                } else {
                    result.setCode(ResultEnum.EREOR.getCode());
                    result.setMsg("userId不能为空！");
                }
            }
            return result;
        } catch (Exception exception) {
            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
        } finally {
            // 日志
            logService.logAdd(dataPageVO.toString(), "获取当前用户的问卷信息", String.valueOf(result.getCode()), result.toString(), userInfo, request);
            return result;
        }
    }

    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    @ApiOperation("问卷下发")
    @PostMapping("bindPaper")
    public Result bindPaper(
            @RequestParam(value = "AreaId", required = true) String areaId,
            @RequestParam(value = "PaperId", required = true) String paperId,
            @RequestParam(value = "BeginTime", required = true) String beginTime,
            @RequestParam(value = "EndTime", required = true) String endTime,
            HttpServletRequest request) {
        String token = request.getHeader("token");
        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        Result result = new Result();
        boolean isSucess = false;
        try {
            if (userInfo == null) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("凭证已过期，请重新登录");
                return result;
            } else {

                if (null != areaId && !areaId.equals("")) {
                    String areaIds[] = areaId.split(",");
                    List<PaperDepart> paperDeparts = new ArrayList<>();
                    PaperDepart paperDepart = null;
                    Map<String, Object> param = null;
                    for (int i = 0; i < areaIds.length; i++) {
                        param = new HashMap<>();
                        param.put("parerId", paperId);
                        param.put("depId", areaIds[i]);
                        List<Map<String, Object>> list = wenjuanService.checkBing(param);
                        if (list.size() == 0) {
                            paperDepart = new PaperDepart();
                            paperDepart.setPaperId(paperId);
                            paperDepart.setDepartId(areaIds[i]);
                            paperDepart.setCreateUser(userInfo.getUserId());
                            paperDeparts.add(paperDepart);
                        }
                    }
                    if (wenjuanService.bindPaper(paperDeparts)) {
                        isSucess = true;
                    } else {
                        isSucess = false;
                    }
                }
                if (isSucess) {
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg("下发问卷成功!");
                    return result;
                } else {
                    result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                    result.setMsg("下发问卷失败!");
                    return result;
                }
            }
        } catch (Exception exception) {
            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
        }
        return result;
    }

    @ApiOperation("问卷提交")
    @PostMapping("subMitExamPaper")
    public Result subMitExamPaper(@RequestBody SubMitExamPaperDto subMitExamPaperDto,
                                  HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("token");
        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        Result result = new Result();
        if (null == userInfo) {
            result.setCode(ResultEnum.EREOR.getCode());
            result.setMsg("凭证已过期，请重新登录");
            return result;
        }
        List<Answer> answers = subMitExamPaperDto.getAnswers();
        Integer paperId = subMitExamPaperDto.getPaperId();

        boolean returnResult = true;

        List<PaperFinsh> paperFinshes = new ArrayList<>();
        PaperFinsh paperFinsh;
        for (int j = 0; j < answers.size(); j++) {
            paperFinsh = new PaperFinsh();
            paperFinsh.setAnswer(answers.get(j).getAnswerName());
            paperFinsh.setAnswerId(answers.get(j).getId());
            paperFinsh.setPqId(answers.get(j).getQuestionId());
            paperFinsh.setPaperId(paperId);
            paperFinsh.setCreateUser(userInfo.getUserId());
            paperFinsh.setAreaCode(userInfo.getAreaCode());
            paperFinshes.add(paperFinsh);
        }
        returnResult = wenjuanService.submitWenJuan(paperFinshes);

        if (returnResult) {
            result.setCode(ResultEnum.SUCCESS.getCode());
            Map<String, Object> map = new HashMap<>();
            map.put("V_USER", userInfo.getUserId());
            map.put("PAR_ID", paperId);
            result.setData(wenjuanService.getPaPerScoreResult(map));
            result.setMsg("提交成功！");
        } else {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setData("");
            result.setMsg("提交失败！");
        }

        return result;
    }

    @ApiOperation("问卷提交")
    @PostMapping("subMitExamPaperV2")
    public Result subMitExamPaperV2(@RequestBody SubMitExamPaperDto subMitExamPaperDto,
                                    HttpServletRequest request, HttpServletResponse response) {
//        String token = request.getHeader("token");
//        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        Result result = new Result();
//        if (null == userInfo) {
//            result.setCode(ResultEnum.EREOR.getCode());
//            result.setMsg("凭证已过期，请重新登录");
//            return result;
//        }
        String userName = subMitExamPaperDto.getUserName();
        String phone = subMitExamPaperDto.getPhone();

        if (null == userName || userName.equals("") || null == phone || phone.equals("")) {
            result.setCode(ResultEnum.EREOR.getCode());
            result.setMsg("请输入姓名和电话哟！");
            return result;
        }

        List<Answer> answers = subMitExamPaperDto.getAnswers();
        Integer paperId = subMitExamPaperDto.getPaperId();

        boolean returnResult = true;

        List<PaperFinsh> paperFinshes = new ArrayList<>();
        PaperFinsh paperFinsh;
        int qs = 100 / (answers.size()-1);
        System.out.println("共" + answers.size() + "题，每题" + qs + "分");
        int count = 0;
        double score = 0.0;
        for (int j = 0; j < answers.size(); j++) {
            Integer id = answers.get(j).getId();
            Integer questionId = answers.get(j).getQuestionId();
            String answerName = answers.get(j).getAnswerName();
            paperFinsh = new PaperFinsh();
            paperFinsh.setAnswer(answerName);
            paperFinsh.setAnswerId(id);
            paperFinsh.setPqId(questionId);
            paperFinsh.setPaperId(paperId);
            paperFinsh.setCreateUser("");
            paperFinsh.setAreaCode("");
            paperFinsh.setUserName(userName);
            paperFinsh.setPhone(phone);
            paperFinshes.add(paperFinsh);

            Answer answer = new Answer();
            answer.setQuestionId(questionId);
            answer.setId(id);
            boolean answer1 = wenjuanService.isAnswer(answer);
            if (answer1) {
                System.out.println(questionId + answerName + " 答对！");
                count++;
            } else {
                System.out.println(questionId + answerName + " 答错！");
            }
        }
        System.out.println("答对" + count + "题");
        if (count == answers.size()-1) {
            score = 100;
        } else {
            score = count * qs;
        }
        UserScore userScore = new UserScore();
        userScore.setUserName(userName);
        userScore.setUserPhone(phone);
        userScore.setPaperId(paperId);
        userScore.setScore(score);

        System.out.println(userName + " " + phone + "得到：" + score + "分");
        boolean b = wenjuanService.submitWenJuanScore(userScore);
        returnResult = wenjuanService.submitWenJuan(paperFinshes);

        if (returnResult) {
            result.setCode(ResultEnum.SUCCESS.getCode());
            Map<String, Object> map = new HashMap<>();
            map.put("userNmae", userName);
            map.put("phone", phone);
            map.put("score", score);
            result.setData(map);
            result.setMsg("提交成功！");
        } else {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setData("");
            result.setMsg("提交失败！");
        }

        return result;
    }


    @ApiOperation("问题修改")
    @PostMapping("questionUpdate")
    public Result questionUpdate(@RequestBody WenJuanPDto wenJuanPDto, String paperId,
                                 HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        Result result = new Result();
        if (null == userInfo) {
            result.setCode(ResultEnum.EREOR.getCode());
            result.setMsg("凭证已过期，请重新登录");
            return result;
        }
        Question question = new Question();
        question.setId(Integer.valueOf(wenJuanPDto.getQuestionId()));
        question.setQuestionName(wenJuanPDto.getQuestionName());
//        question.setQuestionImg(wenJuanPDto.getQuestionImg());
        question.setQuestionClass(String.valueOf(Integer.parseInt(wenJuanPDto.getQuestionClass())));
        if (wenjuanService.updateQuestion(question, wenJuanPDto.getPaperId(), wenJuanPDto)) {
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData("");
            result.setMsg("提交成功");
        } else {
            result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
            result.setData("");
            result.setMsg("提交失败");
        }

        return result;
    }

    @ApiOperation("问题删除")
    @PostMapping("deleteQuestionFromPaper")
    public Result deleteQuestionFromPaper(@RequestBody Question question, @RequestParam(value = "paperId", required = true) String paperId,
                                          HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        Result result = new Result();
        if (null == userInfo) {
            result.setCode(ResultEnum.EREOR.getCode());
            result.setMsg("凭证已过期，请重新登录");
            return result;
        }


        if (wenjuanService.deleteQuestionFromPaper(question, paperId)) {
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData("");
            result.setMsg("提交成功");
        } else {
            result.setCode(ResultEnum.DB_QUERY_FAILURE.getCode());
            result.setData("");
            result.setMsg("未查询到记录");
        }


        result.setData(question);
        return result;
    }

    @ApiOperation("问题新增")
    @PostMapping("questionAdd")
    public Result questionAdd(@RequestBody WenJuanPDto wenJuanPDto,
                              HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
        Result result = new Result();
        if (null == userInfo) {
            result.setCode(ResultEnum.EREOR.getCode());
            result.setMsg("凭证已过期，请重新登录");
            return result;
        }
        Question question = new Question();
        question.setCreateTime(DateUtil.date());
        question.setCreateUser(userInfo.getUserId());
        question.setQuestionName(wenJuanPDto.getQuestionName());
        question.setAreaCode(userInfo.getAreaCode());
        question.setState(1);
//        question.setQuestionImg(wenJuanPDto.getQuestionImg());
        question.setQuestionClass(String.valueOf(Integer.parseInt(wenJuanPDto.getQuestionClass())));
        if (wenjuanService.saveQuestion(question, wenJuanPDto.getPaperId(), wenJuanPDto)) {
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData("");
            result.setMsg("提交成功");
        } else {
            result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
            result.setData("");
            result.setMsg("提交失败");
        }

        return result;
    }


//    @PostMapping("/ExamPaperTj")
//    @ApiOperation(value = "问卷结果统计")
//    public Result ExamPaperTj(HttpServletRequest request, HttpServletResponse response) {
//        Result result = new Result();
//        String token = request.getHeader("token");
//        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
//        String orgCode = userInfo.getDepartId();
//        try {
//            if (null == userInfo) {
//                result.setCode(ResultEnum.EREOR.getCode());
//                result.setMsg("凭证已过期，请重新登录");
//                return result;
//            }
//            JsonObject jsonObject = getRequestPayloadUtil.getRequestPayload(request);
//            String type = "";
//            if (null != jsonObject && jsonObject.size() > 0 && jsonObject.has("type")) {
//                type = jsonObject.get("type").getAsString();
//            }
//            int paperId=0;
//            if(null != jsonObject && jsonObject.size() > 0 && jsonObject.has("paperId"))
//            {
//                paperId = jsonObject.get("paperId").getAsInt();
//            }
//            String areaId="";
//            if(null != jsonObject && jsonObject.size() > 0 && jsonObject.has("areaId"))
//            {
//                areaId = jsonObject.get("areaId").getAsString();
//            }
//            // 查数据
//            ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
//            List<Record> list = wenjuanService.ExamPaperTj(orgCode, type, currUser,paperId,areaId);
//            for (Record record : list) {
//                if (record != null) {
//                    arrayList.add(record.getColumns());
//                } else {
//                    break;
//                }
//            }
//            result.setCode(ResultEnum.SUCCESS.getCode());
//            result.setMsg("获取数据成功");
//            result.setData(arrayList);
//
//            return result;
//        } catch (Exception exception) {
//            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
//        } finally {
//            // 日志
//            logService.logAdd("", "问卷结果统计", String.valueOf(result.getCode()), result.toString(), userInfo, request);
//            return result;
//        }
//    }
//
//    @PostMapping("/ExamPaperTjTable")
//    @ApiOperation(value = "问卷结果统计列表")
//    public Result ExamPaperTjTable(@RequestBody String body, HttpServletRequest request, HttpServletResponse response) {
//        Result result = new Result();
//        String token = request.getHeader("token");
//        UserInfo userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
//        String orgCode = userInfo.getDepartId();
//        try {
//            if (null == userInfo) {
//                result.setCode(ResultEnum.EREOR.getCode());
//                result.setMsg("凭证已过期，请重新登录");
//                return result;
//            }
//            Gson json=new Gson();
//            JsonObject jsonObject = json.fromJson(body.toString(), JsonObject.class);
//            //JsonObject jsonObject = getRequestPayloadUtil.getRequestPayload(request);
//            String type = "";
//            if (null != jsonObject && jsonObject.size() > 0 && jsonObject.has("type")) {
//                type = jsonObject.get("type").getAsString();
//            }
//            int currentPage = jsonObject.get("currentPage").getAsInt();
//            int pageSize = jsonObject.get("pageSize").getAsInt();
//            String paperName="";
//            String areaName="";
//            if (null != jsonObject && jsonObject.size() > 0 && jsonObject.has("paperName")) {
//                paperName = jsonObject.get("paperName").getAsString();
//            }
//            if (null != jsonObject && jsonObject.size() > 0 && jsonObject.has("areaName")) {
//                areaName = jsonObject.get("areaName").getAsString();
//            }
//            // 查数据
//            ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
//            Page<Record> list = wenjuanService.ExamPaperTjTable(currentPage,pageSize,orgCode, type, currUser,paperName,areaName);
//            result.setCode(ResultEnum.SUCCESS.getCode());
//            result.setMsg("获取数据成功");
//            result.setData(pageToMap(list));
//
//            return result;
//        } catch (Exception exception) {
//            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
//        } finally {
//            // 日志
//            logService.logAdd(body, "问卷结果统计列表", String.valueOf(result.getCode()), result.toString(), userInfo, request);
//            return result;
//        }
//    }

//    /*开发人：王永福 时间：20210909 广告列表*/
//    @PostMapping("/AdvertisementList")
//    @ApiOperation(
//            value = "广告列表"//简要说明
//    )
//    public Result AdvertisementList(HttpServletRequest request, HttpServletResponse response) {
//        Result result = new Result();
//        //token校验
//        String token = request.getHeader(ConfInfo.V_TOKEN);
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        JsonObject jsonObject = getRequestPayloadUtil.getRequestPayload(request);
//        int currentPage = Integer.parseInt(jsonObject.get("currentPage").toString());
//        int pageSize = Integer.parseInt(jsonObject.get("pageSize").toString());
//        String perform="";
//        String userCode = currUser.getOrgCode();
//        if(jsonObject.has("perform")){
//            perform= jsonObject.get("perform").getAsString();
//            userCode=currUser.getWyId();
//        }
//
//        try {
//            if (null == currUser) {
//                return Result.TokenExp();
//            }
//            Page<Record> list = wenjuanService.AdvertisementList(currentPage, pageSize, userCode,currUser);
//            result.setCode(ResultEnum.SUCCESS.getCode());
//            result.setMsg("获取数据成功");
//            result.setData(pageToMap(list));
//        } catch (Exception exception) {
//            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
//        } finally {
//            //添加日志
//            logUtil.LogAdd("获取广告列表", (null == currUser ? "" : currUser.getUserCode()),
//                    (request == null ? "" : request.getRemoteAddr()),
//                    (request == null ? "" : request.getRequestURL().toString()), null,
//                    Integer.toString(result.getCode()), JSONObject.toJSONString(result),
//                    (!result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? (null == result.getData() ? "" : result.getData().toString()) : ""));
//            return result;
//        }
//    }

    /*开发人：王永福 时间：20210909 广告新增*/
//    @PostMapping("/AdvertisementAdd")
//    @ApiOperation(
//            value = "添加广告"
//    )
//    public Result AdvertisementAdd(@RequestBody Advertisement advment,
//                                   HttpServletRequest request, HttpServletResponse response) {
//        Result result = new Result();
//        //token校验
//        String token = request.getHeader(ConfInfo.V_TOKEN);
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        try {
//            if (null == currUser) {
//                return Result.TokenExp();
//            }
//            advment.setCreateDate(new Date(System.currentTimeMillis()))
//                    .setCreateUser(currUser.getUserCode())
//                    .setOrgCode(currUser.getOrgCode())
//                    .setSTATE(1);
////            wenjuanService.Advertisementsave(advment);
//            if (wenjuanService.Advertisementsave(advment)) {
//                result.setCode(ResultEnum.SUCCESS.getCode());
////                result.setData(advment);
//                result.setMsg("提交成功");
//            } else {
//                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
////                result.setData("");
//                result.setMsg("提交失败");
//            }
//        } catch (Exception exception) {
//            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
//        } finally {
//            //添加日志
//            logUtil.LogAdd("添加广告", (null == currUser ? "" : currUser.getUserCode()),
//                    (request == null ? "" : request.getRemoteAddr()),
//                    (request == null ? "" : request.getRequestURL().toString()),
//                    JSONObject.toJSONString(advment),
//                    Integer.toString(result.getCode()), JSONObject.toJSONString(result),
//                    (!result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? (null == result.getData() ? "" : result.getData().toString()) : ""));
//            return result;
//        }
//    }
//
//    /*开发人：王永福 时间：20210909 广告修改*/
//    @ApiOperation("广告修改")
//    @PostMapping("AdvertisementUpdate")
//    public Result AdvertisementUpdate(@RequestBody Advertisement advment,
//                                      HttpServletRequest request, HttpServletResponse response) {
//        String token = request.getHeader("v_token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        Result result = new Result();
//        if (null == currUser) {
//            result.setCode(ResultEnum.EREOR.getCode());
//            result.setMsg("凭证已过期，请重新登录");
//            return result;
//        }
//        if (wenjuanService.AdvertisementUpdate(advment)) {
//            result.setCode(ResultEnum.SUCCESS.getCode());
//            result.setData("");
//            result.setMsg("修改成功");
//        } else {
//            result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//            result.setData("");
//            result.setMsg("提交失败");
//
//        }
//        return result;
//    }
//
//    /*开发人：王永福 时间：20210909 广告删除*/
//    @ApiOperation("广告删除")
//    @PostMapping("deleteAdvertisement")
//    public Result deleteAdvertisement(@RequestBody Advertisement advment,
//                                      HttpServletRequest request, HttpServletResponse response) {
//        String token = request.getHeader("v_token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        Result result = new Result();
//        if (null == currUser) {
//            result.setCode(ResultEnum.EREOR.getCode());
//            result.setMsg("凭证已过期，请重新登录");
//            return result;
//        }
//        if (wenjuanService.deleteAdvertisement(advment, advment.getID())) {
//            result.setCode(ResultEnum.SUCCESS.getCode());
//            result.setData("");
//            result.setMsg("删除成功");
//        } else {
//            result.setCode(ResultEnum.DB_QUERY_FAILURE.getCode());
//            result.setData("");
//            result.setMsg("未查询到记录");
//        }
//        result.setData(advment);
//        return result;
//    }
//
//    /*开发人：王永福 时间：20210909 广告列表*/
//    @PostMapping("/wyshList")
//    @ApiOperation(
//            value = "物业审核列表"//简要说明
//    )
//    public Result wyshList(HttpServletRequest request, HttpServletResponse response) {
//        Result result = new Result();
//        //token校验
//        String token = request.getHeader(ConfInfo.V_TOKEN);
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        JsonObject jsonObject = getRequestPayloadUtil.getRequestPayload(request);
//        int currentPage = Integer.parseInt(jsonObject.get("currentPage").toString());
//        int pageSize = Integer.parseInt(jsonObject.get("pageSize").toString());
//        int p_state = jsonObject.get("p_state").getAsInt();
//        String usertel = jsonObject.get("usertel").getAsString();
//        String username = jsonObject.get("userName").getAsString();
//        String wyname = jsonObject.get("wyname").getAsString();
//        String usercode = currUser.getOrgCode();
//        try {
//            if (null == currUser) {
//                return Result.TokenExp();
//            }
//            Page<Record> list = wenjuanService.wyshList(currentPage, pageSize, usercode,p_state,usertel,username,wyname);
//            result.setCode(ResultEnum.SUCCESS.getCode());
//            result.setMsg("获取数据成功");
//            result.setData(pageToMap(list));
//        } catch (Exception exception) {
//            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
//        } finally {
//            //添加日志
//            logUtil.LogAdd("获取物业审核列表", (null == currUser ? "" : currUser.getUserCode()),
//                    (request == null ? "" : request.getRemoteAddr()),
//                    (request == null ? "" : request.getRequestURL().toString()), null,
//                    Integer.toString(result.getCode()), JSONObject.toJSONString(result),
//                    (!result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? (null == result.getData() ? "" : result.getData().toString()) : ""));
//            return result;
//        }
//    }
//
//    /*开发人：王永福 时间：20210909 物业新增*/
//    @PostMapping("/wyshAdd")
//    @ApiOperation(
//            value = "添加物业审核信息"
//    )
//    public Result wyshAdd(@RequestBody WySh wysh, HttpServletRequest request, HttpServletResponse response) {
//        Result result = new Result();
//        //token校验
//        String token = request.getHeader(ConfInfo.V_TOKEN);
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        try {
//            if (null == currUser) {
//                return Result.TokenExp();
//            }
//            boolean isWyExist = wenjuanService.checkWuYeIsExist(wysh.getWyZz());
//            if(isWyExist){
//                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//                result.setMsg("营业执照:"+wysh.getWyZz()+"已被注册");
//                return result;
//            }
//            boolean isExist = wenjuanService.checkCodeIsExist(wysh.getUserTel());
//            if(isExist){
//                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//                result.setMsg("号码:"+wysh.getUserTel()+"已被注册");
//                return result;
//            }
//            wysh.setCreateTime(new Date(System.currentTimeMillis()))
//                    .setCreateUser(currUser.getOpenid())
////                    .setOrgCode(currUser.getOrgCode())
//                    .setState(1);
//            if (wenjuanService.wyshAdd(wysh)) {
//                result.setCode(ResultEnum.SUCCESS.getCode());
//                result.setMsg("提交成功");
//            } else {
//                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//                result.setMsg("提交失败");
//            }
//        } catch (Exception exception) {
//            result = Result.error(ResultEnum.DB_QUERY_FAILURE, exception.toString());
//        } finally {
//            //添加日志
//            logUtil.LogAdd("添加审核", (null == currUser ? "" : currUser.getUserCode()),
//                    (request == null ? "" : request.getRemoteAddr()),
//                    (request == null ? "" : request.getRequestURL().toString()),
//                    JSONObject.toJSONString(wysh),
//                    Integer.toString(result.getCode()), JSONObject.toJSONString(result),
//                    (!result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? (null == result.getData() ? "" : result.getData().toString()) : ""));
//            return result;
//        }
//    }
//
//    @ApiOperation("修改物业信息")
//    @PostMapping("wyshUpdate")
//    public Result wyshUpdate(@RequestBody WySh wysh, HttpServletRequest request, HttpServletResponse response) {
//        String token = request.getHeader("v_token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        Result result = new Result();
//        if (null == currUser) {
//            result.setCode(ResultEnum.EREOR.getCode());
//            result.setMsg("凭证已过期，请重新登录");
//            return result;
//        }
//        if (wenjuanService.wyshUpdate(wysh)) {
//            result.setCode(ResultEnum.SUCCESS.getCode());
//            result.setData("");
//            result.setMsg("修改成功");
//        } else {
//            result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//            result.setData("");
//            result.setMsg("提交失败");
//        }
//        return result;
//    }
//
//    @ApiOperation("统计该用户未填写的问卷数量")
//    @PostMapping("countNotFilledPaper")
//    public Result countNotFilledPaper(HttpServletRequest request) {
//        String token = request.getHeader("v_token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        Result result = new Result();
//        if (null == currUser) {
//            result.setCode(ResultEnum.EREOR.getCode());
//            result.setMsg("凭证已过期，请重新登录");
//            return result;
//        }
//        int i = wenjuanService.countNotFilledPaper(currUser);
//        if (i >= 0) {
//            result.setCode(ResultEnum.SUCCESS.getCode());
//            result.setData(i);
//            result.setMsg("获取成功！");
//        } else {
//            result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//            result.setMsg("获取失败或数据异常！");
//        }
//        return result;
//    }
//
//    /*开发人：王永福 时间：20210909 物业删除*/
//    @ApiOperation("物业删除")
//    @PostMapping("deletewysh")
//    public Result deletewysh(@RequestBody WySh wysh, HttpServletRequest request, HttpServletResponse response) {
//        String token = request.getHeader("v_token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        Result result = new Result();
//        if (null == currUser) {
//            result.setCode(ResultEnum.EREOR.getCode());
//            result.setMsg("凭证已过期，请重新登录");
//            return result;
//        }
//        if (wenjuanService.deletewysh(wysh, wysh.getId())) {
//            result.setCode(ResultEnum.SUCCESS.getCode());
//            result.setData("");
//            result.setMsg("删除成功");
//        } else {
//            result.setCode(ResultEnum.DB_QUERY_FAILURE.getCode());
//            result.setData("");
//            result.setMsg("未查询到记录");
//        }
//        result.setData(wysh);
//        return result;
//    }
//
//    /*开发人：王永福 时间：20210909 审核信息*/
//    @ApiOperation("物业审核")
//    @PostMapping("wysh")
//    public Result wysh(WySh wysh, HttpServletRequest request, HttpServletResponse response) {
//        String token = request.getHeader("v_token");
//        CurrUser currUser = JwtUtil.getCurrUserFromToken(token);
//        Result result = new Result();
//        JsonObject jsonObject = getRequestPayloadUtil.getRequestPayload(request);
//        String sh_dsc = "";
//        int sh_state = Integer.parseInt(jsonObject.get("sh_state").toString());
//        sh_dsc = jsonObject.get("sh_dsc").toString();
//        int wy_id = Integer.parseInt(jsonObject.get("id").toString());
//
//        if (null == currUser) {
//            result.setCode(ResultEnum.EREOR.getCode());
//            result.setMsg("凭证已过期，请重新登录");
//            return result;
//        }
//
//        String userCode = currUser.getUserCode();
//        if (sh_state == 2) {
//            sh_dsc = "通过";
//            wysh = WySh.dao.findById(wy_id);
//            if(null!=wysh){
//                //工号唯一校验
//                boolean isExist = wenjuanService.checkCodeIsExist(wysh.getUserTel());
//                if (isExist) {
//                    result.setCode(ResultEnum.EREOR.getCode());
//                    result.setMsg("工号:"+wysh.getUserTel()+"已经存在，请做驳回处理！");
//                    return result;
//                }
//                HashMap<String,String> headMap = new HashMap<>();
//                headMap.put("v_token",token);
//                JSONObject contentJson = new JSONObject();
//                contentJson.put("attachmentList",new JSONArray());
//                contentJson.put("id",null);
//
//                JSONObject sysOrgJson = new JSONObject();
//                sysOrgJson.put("orgName",wysh.getWyName());
//                sysOrgJson.put("tyshbm",wysh.getWyZz());
//                sysOrgJson.put("orgType",5);
//                sysOrgJson.put("parentCode","01");
//                contentJson.put("sysOrg",sysOrgJson);
//                String resultOrg = HttpClientUtil.doPostJsonHeader("http://localhost:10085/api-auth/org/save",headMap,contentJson.toString());
//                JSONObject resultOrgJson = JSONObject.parseObject(resultOrg);
//                SysOrg sysOrg=null;
//                if(resultOrgJson.getIntValue("code")==200){
//                    //架构添加成功
//                    sysOrg = JSON.toJavaObject(resultOrgJson.getJSONObject("data"),SysOrg.class);
//
//                    contentJson = new JSONObject();
//                    contentJson.put("id",null);
//                    contentJson.put("orgCode",sysOrg.getOrgCode());
//                    contentJson.put("password","OTZFNzkyMTg5NjVFQjcyQzkyQTU0OURENUEzMzAxMTI=");
//                    contentJson.put("roleCode","003");
//                    contentJson.put("roleCodes","003");
//                    contentJson.put("userCode",wysh.getUserTel());
//                    contentJson.put("userName",wysh.getWyName());
//                    String resultUser = HttpClientUtil.doPostJsonHeader("http://localhost:10085/api-auth/user/save",headMap,contentJson.toString());
//                    JSONObject resultUserJson = JSONObject.parseObject(resultUser);
//                    if(resultUserJson.getIntValue("code")==200)
//                    {
//                        //用户添加成功
//                        SysUser sysUser = JSON.toJavaObject(resultOrgJson.getJSONObject("data"),SysUser.class);
//                        if(wenjuanService.wysh(wysh, userCode, sh_dsc, sh_state, wy_id)){
//                            result.setCode(ResultEnum.SUCCESS.getCode());
//                            result.setData("");
//                            result.setMsg("审核成功");
//                        }
//                        else{
//                            result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//                            result.setData("");
//                            result.setMsg("审核失败");
//                        }
//                    }
//                    else{
//
//                        sysOrg.setStatus(0);
//                        sysOrg.update();
//
//                        result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//                        result.setData("");
//                        result.setMsg(resultUserJson.getString("msg").replace("工号","工号:"+wysh.getUserTel())+",请做驳回处理");
//                    }
//
//                }
//                else{
//                    result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//                    result.setData("");
//                    result.setMsg(resultOrgJson.getString("msg")+",请做驳回处理");
//                }
//            }
//        }
//        else{
//            if(wenjuanService.wysh(wysh, userCode, sh_dsc, sh_state, wy_id)){
//                result.setCode(ResultEnum.SUCCESS.getCode());
//                result.setData("");
//                result.setMsg("审核成功");
//            }
//            else{
//                result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//                result.setData("");
//                result.setMsg("审核失败");
//            }
//        }


//        if (wenjuanService.wysh(wysh, userCode, sh_dsc, sh_state, wy_id)) {
////            wenjuanService.getorgcode(wysh);
//            String orgcode = getOrgCode(wenjuanService.getorgcode(wy_id), "1");
//            wenjuanService.updateorg(wysh, userCode, orgcode, wy_id);
//
//
//
//                result.setCode(ResultEnum.SUCCESS.getCode());
//                result.setData("");
//                result.setMsg("审核成功");
//
//
//        } else {
//            result.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
//            result.setData("");
//            result.setMsg("审核失败");
//        }
//        return result;
//    }

    //生成机构编码
//    public String getOrgCode(String parentCode, String type) {
//        Date currentTime = new Date();
//        String dateStr = "" + currentTime.getTime();
//        String a = "00000";
//        type = Integer.valueOf(type) < 10 ? "0" + type : type;
//        String orgcode = "T";
//        int step = 1;
//        if (parentCode.equals("0") || parentCode.isEmpty())
//            step = 1;
//        else if ("T".equals(parentCode.substring(0, 1)) && parentCode.length() == 10)
//            step = Integer.valueOf(parentCode.substring(3, 5)) + 1;
//        else {
//            step = 0;
//        }
//        String steps = step < 10 ? "0" + step : "" + step;
//        String count = "" + (wenjuanService.getChildrenCount(parentCode) + 1);
//        count = a.substring(0, 5 - count.length()) + count;
//        orgcode = step == 0 ? dateStr : orgcode + type + steps + count;
//        return orgcode;
//    }

//    @PostMapping("/test")
//    public Result testPaperScore(@RequestBody JSONObject object,HttpServletRequest request){
//
//        Map<String,Object> map=new HashMap<>();
//        map.put("V_USER",object.get("uId"));
//        map.put("PAR_ID",object.get("pId"));
//        return Result.success(wenjuanService.getPaPerScoreResult(map));
//    }

}
